<template>
  <view class="container">
    <view class="header">
      <text class="title">支付宝沙箱支付</text>
    </view>
    
    <view class="order-info" v-if="order">
      <view class="info-item">
        <text class="label">订单号：</text>
        <text class="value">{{ order.orderId }}</text>
      </view>
      <view class="info-item">
        <text class="label">订单金额：</text>
        <text class="value price">¥{{ order.totalPrice }}</text>
      </view>
      <view class="info-item">
        <text class="label">订单状态：</text>
        <text class="value" :class="getStatusClass(order.status)">{{ formatStatus(order.status) }}</text>
      </view>
    </view>
    
    <view class="payment-section">
      <view class="alipay-logo">
        <image src="/static/alipay-logo.png" mode="aspectFit"></image>
      </view>
      
      <!-- 支付状态提示 -->
      <view class="status-hint" v-if="paymentUrl">
        <text class="hint-icon">✓</text>
        <text class="hint-text">支付链接已生成</text>
      </view>
      
      <!-- 支付链接展示 -->
      <view class="payment-url" v-if="paymentUrl">
        <text class="url-label">支付链接：</text>
        <text class="url-text">{{ shortUrl }}</text>
        <button class="copy-button" @click="copyUrl" size="mini">复制链接</button>
      </view>
      
      <button class="pay-button" @click="handleAlipay" :disabled="isPaying">
        {{ getButtonText() }}
      </button>
      
      <button class="cancel-button" @click="goBack" :disabled="isPaying">取消支付</button>
    </view>
    
    <view class="tips">
      <text class="tip-title">💡 沙箱支付说明：</text>
      <text class="tip-text">1. 点击"立即支付"会在新窗口打开支付宝沙箱支付页面</text>
      <text class="tip-text">2. 使用沙箱账号登录并完成支付（账号信息见沙箱配置）</text>
      <text class="tip-text">3. 支付完成后，系统会自动检测并跳转到订单详情</text>
      <text class="tip-text">4. 如未自动跳转，请手动返回查看订单状态</text>
    </view>
    
    <!-- 轮询检查提示 -->
    <view class="checking-status" v-if="isChecking">
      <text class="checking-text">正在检查支付状态...</text>
      <text class="checking-count">已检查 {{ checkCount }} 次</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { orderApi } from '@/common/api/order.js';

const order = ref(null);
const isPaying = ref(false);
const orderId = ref('');
const paymentUrl = ref('');
const isChecking = ref(false);
const checkCount = ref(0);

// 格式化订单状态
const formatStatus = (status) => {
  const statusMap = {
    'pending': '待支付',
    'paid': '已支付',
    'completed': '已完成',
    'canceled': '已取消'
  };
  return statusMap[status] || status;
};

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    'pending': 'status-pending',
    'paid': 'status-paid',
    'completed': 'status-completed',
    'canceled': 'status-canceled'
  };
  return classMap[status] || '';
};

// 获取按钮文字
const getButtonText = () => {
  if (isPaying.value) {
    return '正在处理...';
  }
  if (paymentUrl.value) {
    return '重新打开支付页面';
  }
  return '立即支付';
};

// 计算短链接用于显示
const shortUrl = computed(() => {
  if (!paymentUrl.value) return '';
  const url = paymentUrl.value;
  if (url.length > 50) {
    return url.substring(0, 50) + '...';
  }
  return url;
});

// 页面加载时获取订单信息
onLoad((options) => {
  if (options.orderId) {
    orderId.value = options.orderId;
    fetchOrderInfo();
  }
});

// 获取订单信息
const fetchOrderInfo = async () => {
  try {
    const res = await orderApi.getOrderDetail(orderId.value);
    if (res.code === 200) {
      order.value = res.data;
      
      // 如果订单已支付，提示并返回
      if (res.data.status === 'paid') {
        uni.showModal({
          title: '提示',
          content: '该订单已支付',
          showCancel: false,
          success: () => {
            uni.navigateBack();
          }
        });
      }
    } else {
      uni.showToast({
        title: '获取订单信息失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取订单信息失败:', error);
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    });
  }
};

// 处理支付宝支付
const handleAlipay = async () => {
  if (isPaying.value) return;
  
  // 如果已有支付链接，直接打开
  if (paymentUrl.value) {
    openPaymentUrl();
    return;
  }
  
  isPaying.value = true;
  
  try {
    console.log('📝 创建支付宝支付订单...');
    
    // 调用后端接口创建支付宝支付
    const res = await orderApi.createAlipayPayment(orderId.value);
    
    if (res.code === 200 && res.data.paymentUrl) {
      paymentUrl.value = res.data.paymentUrl;
      
      console.log('✅ 支付宝支付订单创建成功');
      console.log('💡 支付链接:', paymentUrl.value);
      
      // 开始检查支付状态
      startCheckingStatus();
      
      // 打开支付页面
      openPaymentUrl();
      
      uni.showToast({
        title: '支付链接已生成',
        icon: 'success'
      });
      
      isPaying.value = false;
    } else {
      uni.showToast({
        title: res.message || '创建支付失败',
        icon: 'none'
      });
      isPaying.value = false;
    }
  } catch (error) {
    console.error('❌ 支付宝支付失败:', error);
    uni.showToast({
      title: '支付请求失败',
      icon: 'none'
    });
    isPaying.value = false;
  }
};

// 打开支付链接
const openPaymentUrl = () => {
  if (!paymentUrl.value) return;
  
  // #ifdef H5
  // 在H5环境下，在新窗口打开支付链接
  window.open(paymentUrl.value, '_blank');
  uni.showToast({
    title: '已在新窗口打开支付页面',
    icon: 'success',
    duration: 2000
  });
  // #endif
  
  // #ifndef H5
  // 在小程序环境下，复制链接到剪贴板
  uni.setClipboardData({
    data: paymentUrl.value,
    success: () => {
      uni.showModal({
        title: '支付链接已复制',
        content: '请在浏览器中粘贴链接完成支付',
        showCancel: false
      });
    }
  });
  // #endif
};

// 复制支付链接
const copyUrl = () => {
  if (!paymentUrl.value) return;
  
  uni.setClipboardData({
    data: paymentUrl.value,
    success: () => {
      uni.showToast({
        title: '链接已复制',
        icon: 'success'
      });
    },
    fail: () => {
      uni.showToast({
        title: '复制失败',
        icon: 'none'
      });
    }
  });
};

// 返回上一页
const goBack = () => {
  stopCheckingStatus();
  uni.navigateBack();
};

// 页面卸载时清除定时器
onUnmounted(() => {
  stopCheckingStatus();
});

// 定时检查支付状态
let statusCheckTimer = null;
const MAX_CHECK_COUNT = 60; // 最多检查60次（3分钟）

const startCheckingStatus = () => {
  // 清除之前的定时器
  stopCheckingStatus();
  
  isChecking.value = true;
  checkCount.value = 0;
  
  console.log('🔄 开始轮询检查支付状态...');
  
  statusCheckTimer = setInterval(async () => {
    checkCount.value++;
    
    // 超过最大检查次数，停止轮询
    if (checkCount.value > MAX_CHECK_COUNT) {
      console.log('⏰ 达到最大检查次数，停止轮询');
      stopCheckingStatus();
      uni.showModal({
        title: '提示',
        content: '支付状态检查超时，请手动刷新订单状态',
        showCancel: false
      });
      return;
    }
    
    try {
      console.log(`🔍 第 ${checkCount.value} 次检查支付状态...`);
      
      const res = await orderApi.checkAlipayStatus(orderId.value);
      
      if (res.code === 200 && res.data) {
        const status = res.data.status;
        
        console.log('📊 当前订单状态:', status);
        
        // 更新本地订单状态
        if (order.value) {
          order.value.status = status;
        }
        
        // 检查订单状态
        if (status === 'paid') {
          // 支付成功
          console.log('✅ 支付成功！');
          stopCheckingStatus();
          
          uni.showModal({
            title: '🎉 支付成功',
            content: '恭喜您！订单支付成功，查看订单详情或返回首页？',
            confirmText: '查看详情',
            cancelText: '返回首页',
            success: (res) => {
              if (res.confirm) {
                // 用户点击"查看详情"，跳转到订单详情页
                uni.redirectTo({
                  url: `/pages/orders/ticket-detail?orderId=${orderId.value}`
                });
              } else {
                // 用户点击"返回首页"，跳转到首页
                uni.switchTab({
                  url: '/pages/index/index'
                });
              }
            }
          });
        } else if (status === 'canceled') {
          // 订单已取消
          console.log('❌ 订单已取消');
          stopCheckingStatus();
          
          uni.showModal({
            title: '订单已取消',
            content: '订单已被取消，是否返回首页？',
            confirmText: '返回首页',
            cancelText: '查看订单',
            success: (res) => {
              if (res.confirm) {
                // 返回首页
                uni.switchTab({
                  url: '/pages/index/index'
                });
              } else {
                // 查看订单列表
                uni.redirectTo({
                  url: '/pages/orders/list-status'
                });
              }
            }
          });
        }
        // 其他状态（pending等）继续轮询
      }
    } catch (error) {
      // 静默处理错误，避免打扰用户
      console.log('⚠️ 查询支付状态时出错:', error.message || error);
      // 继续轮询，不中断
    }
  }, 3000); // 每3秒检查一次
};

// 停止检查支付状态
const stopCheckingStatus = () => {
  if (statusCheckTimer) {
    clearInterval(statusCheckTimer);
    statusCheckTimer = null;
  }
  isChecking.value = false;
  console.log('⏹️ 停止检查支付状态');
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  padding: 40rpx 0;
  background-color: #fff;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.order-info {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  align-items: center;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 28rpx;
  color: #666;
}

.value {
  font-size: 28rpx;
  color: #333;
}

.price {
  color: #ff6600;
  font-weight: bold;
  font-size: 32rpx;
}

.status-pending {
  color: #ff9500;
}

.status-paid {
  color: #07c160;
}

.status-completed {
  color: #10aeff;
}

.status-canceled {
  color: #999;
}

.payment-section {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 40rpx 30rpx;
  text-align: center;
  margin-bottom: 20rpx;
}

.alipay-logo {
  width: 200rpx;
  height: 200rpx;
  margin: 0 auto 40rpx;
  
  image {
    width: 100%;
    height: 100%;
  }
}

.status-hint {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  background-color: #e8f8f5;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.hint-icon {
  font-size: 32rpx;
  color: #07c160;
  margin-right: 10rpx;
}

.hint-text {
  font-size: 28rpx;
  color: #07c160;
}

.payment-url {
  background-color: #f7f7f7;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.url-label {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.url-text {
  font-size: 24rpx;
  color: #333;
  word-break: break-all;
  margin-bottom: 10rpx;
}

.copy-button {
  align-self: flex-end;
  background-color: #108ee9;
  color: #fff;
}

.pay-button {
  width: 100%;
  height: 80rpx;
  background-color: #108ee9;
  color: #fff;
  border-radius: 10rpx;
  font-size: 32rpx;
  margin-bottom: 20rpx;
  
  &:disabled {
    background-color: #cccccc;
  }
}

.cancel-button {
  width: 100%;
  height: 80rpx;
  background-color: #fff;
  color: #666;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  font-size: 32rpx;
}

.tips {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.tip-title {
  display: block;
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.tip-text {
  display: block;
  font-size: 24rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 10rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.checking-status {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  text-align: center;
}

.checking-text {
  display: block;
  font-size: 28rpx;
  color: #108ee9;
  margin-bottom: 10rpx;
}

.checking-count {
  display: block;
  font-size: 24rpx;
  color: #999;
}
</style>